/*
 * @(#)EmailRuleEngineHelper.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.core;

import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import uk.ltd.getahead.dwr.ExecutionContext;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.rules.RuleOperationConstant;
import com.dcivision.rules.dao.RuleBaseObjectDAObject;

/**
 * <p> Class Name: EmailRuleEngineHelper</p>
 * <p> Decription: This class is when up and down,Eable and disable the Rule List, offer some method.</p>
 * 
 * 
 * @author        Samlin Zhang
 * @company       DCIVision Limited
 * @creation date 16/11/2005
 * @version       $Revision: 1.5 $
 */
public class EmailRuleEngineListHelper {

  protected Log log = LogFactory.getLog(this.getClass().getName());

  public EmailRuleEngineListHelper() {

  }
  

  /**
   * enable or disable  a Rule
   * @param allID
   * @param enabled
   * @param ruleType
   * @return
   */
//  public String enableRule(String allID, boolean enabled, String ruleType) {
//    String result = GlobalConstant.TRUE;
//    StringTokenizer strtok = new StringTokenizer(allID);
//    List ruleList = new ArrayList();
//
//    while (strtok.hasMoreTokens()) {
//
//      ruleList.add(new Integer(strtok.nextToken("_")));
//    }
//
//    try {
//      RuleBaseObjectDAObject dao = getDAObjectByClassName(ruleType);
//
//      for (Iterator iter = ruleList.iterator(); iter.hasNext();) {
//        Integer element = (Integer) iter.next();
//        RuleBaseObject rule = (RuleBaseObject) dao.getObjectByID(element);
//        if (enabled) {
//          rule.setRuleEnable(GlobalConstant.TRUE);
//        } else {
//          rule.setRuleEnable(GlobalConstant.FALSE);
//        }
//
//        dao.updateNewObject(rule);
//
//      }
//    } catch (Exception e) {
//      result = GlobalConstant.FALSE;
//      log.error(e);
//    }
//    return result;
//  }
  /**
   * enable or disable  a Rule
   * @param allID
   * @param enabled
   * @param ruleType
   * @return
   */
    public String enableBatchRule(String allID, boolean enabled, String ruleType) {
      String result = GlobalConstant.TRUE;
      StringTokenizer strtok = new StringTokenizer(allID);
      List ruleList = new ArrayList();
      
      while (strtok.hasMoreTokens()) {

        ruleList.add(new Integer(strtok.nextToken("_")));
      }

      if (ruleList.size()==0){
        return "";
      }
      
      try {
        RuleBaseObjectDAObject dao = getDAObjectByClassName(ruleType);

        
        dao.enableBatchObject(ruleList,enabled);
  
      } catch (Exception e) {
        result = GlobalConstant.FALSE;
        log.error(e);
      }
      return result;
    }

/**
 * up or down many rule for once
 * @param allID
 * @param moveUp
 * @param ruleType
 * @return
 */
  public String upBatchRule(String allID, boolean moveUp, String ruleType) {
    String result = GlobalConstant.TRUE;
    StringTokenizer strtok = new StringTokenizer(allID);
    List ruleList = new ArrayList();
    long start1 = System.currentTimeMillis();
    while (strtok.hasMoreTokens()) {
      ruleList.add(new Integer(strtok.nextToken("_")));
    }

    try {
      RuleBaseObjectDAObject dao = getDAObjectByClassName(ruleType);
      dao.upBatchObject(ruleList, moveUp);
       } catch (Exception e) {
      log.error(e);
      result = GlobalConstant.FALSE;
    }
    long time1= System.currentTimeMillis() - start1;
    log.info("BatchUpdate Up or Down time:"+time1);
    return result;
  }
  
  private RuleBaseObjectDAObject getDAObjectByClassName(String ruleType) throws ApplicationException {
    SessionContainer sessionCon = this.getSessionContainer();
    Connection conn = null;
    Class clsDAO = null;
    Constructor conDAO = null;
    RuleBaseObjectDAObject dao = null;
    String majorDAOClassName = null;

    if (RuleOperationConstant.PRIVATE_RULE_FUNCTION.equals(ruleType)) {
      majorDAOClassName = "com.dcivision.dms.dao.EmailArichivePrivateRuleDAObject";
    } else {
      majorDAOClassName = "com.dcivision.dms.dao.EmailArichiveRuleDAObject";
    }

    try {
      conn = DataSourceFactory.getConnection();
      clsDAO = Class.forName(majorDAOClassName);
      conDAO = clsDAO.getConstructor(new Class[] { SessionContainer.class, Connection.class });
      dao = (RuleBaseObjectDAObject) conDAO.newInstance(new Object[] { sessionCon, conn });
      return (dao);
    } catch (java.lang.reflect.InvocationTargetException ite) {
      throw new ApplicationException(ErrorConstant.COMMON_UNKNOWN_DAO, ite, majorDAOClassName);
    } catch (Exception e) {
      throw new ApplicationException(ErrorConstant.COMMON_UNKNOWN_DAO, e, majorDAOClassName);
    }finally{
      try{conn.close();}catch(Exception ignore){}finally{conn=null;}//TC ADD FOR:connection should close
    }
  }

  public SessionContainer getSessionContainer() {
    HttpSession session = ExecutionContext.get().getSession();
    return (SessionContainer) session.getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);

  }
  
  public String dragRule(String sourceID,String targetID,String ruleType){
    String result = GlobalConstant.TRUE;

    try {
      RuleBaseObjectDAObject dao = getDAObjectByClassName(ruleType);
      Integer srcID = TextUtility.parseIntegerObj(sourceID);
      Integer tarID = TextUtility.parseIntegerObj(targetID);
      dao.dragRuleBaseObject(srcID, tarID);
       } catch (Exception e) {
      log.error(e);
      result = GlobalConstant.FALSE;
    }
    //long time1= System.currentTimeMillis() - start1;
    //log.info("BatchUpdate Up or Down time:"+time1);
    return result;
  }
}
